package fr.web325.servlet.api.cart;

import fr.web325.bean.Book;
import fr.web325.bean.Json;
import fr.web325.dao.BookDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/addCart")
public class AddCart extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.得到商品id
        String id = req.getParameter("id");
        JSONObject json = new JSONObject();
        // 2.调用service层方法，根据id查找商品
        BookDao service = new BookDao();
        try {
            fr.web325.bean.Book p = service.getBookById(id);
            System.out.println(p.toString());
            if(p==null){
                resp.getWriter().print(new Json(200,null,"添加失败,请检查ID是否正确!").getRespJson());
                return;
            }
            //3.将商品添加到购物车
            //3.1获得session对象
            HttpSession session = req.getSession();
            //3.2从session中获取购物车对象
            Map<fr.web325.bean.Book, Integer> cart = (Map<fr.web325.bean.Book, Integer>)session.getAttribute("cart");
            //3.3如果购物车为null,说明没有商品存储在购物车中，创建出购物车
            if (cart == null) {
                cart = new HashMap<Book, Integer>();
            }
            //3.4向购物车中添加商品
            Integer count = cart.put(p, 1);

            //3.5如果商品数量不为空，则商品数量+1，否则添加新的商品信息
            if (count != null) {
                cart.put(p, count + 1);
            }
            session.setAttribute("cart", cart);
            resp.getWriter().print(new Json(200,null,"添加成功").getRespJson());
        } catch ( SQLException e) {
            e.printStackTrace();
        }
    }
}
